#ifndef __THREAD_HPP__
#define __THREAD_HPP__
#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <functional>
#include <vector>
using std::cout;
using std::endl;

namespace ThreadModule // 左值引用版本，Thread(print,c);
{

    using func_t = std::function<void(std::string)>;

    class Thread
    {
    private:
        pthread_t _tid;
        std::string _name;
        func_t _func;
        bool _stop;

    public:
        Thread(func_t func, std::string name = "none-name")
            : _func(func), _name(name), _stop(true)
        {
        }

        void Excute()
        {
            _func(_name);
        }

        static void *threadroutine(void *args) // 类内非静态成员函数具有this指针！！！。
        {
            Thread *self = static_cast<Thread *>(args);
            self->Excute();
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadroutine, this);
            if (!n)
            {
                _stop = false;
                return true;
            }
            else
            {
                return false;
            }
        }

        void Detach()
        {
            if (!_stop)
            {
                pthread_detach(_tid);
            }
        }

        void Join()
        {
            if (!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }

        std::string name()
        {
            return _name;
        }

        void Stop()
        {
            if (!_stop)
            {
                _stop = true;
            }
        }

        ~Thread() {}
    };
}

#endif
